package com.shaoshaohuo.app.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.Address;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCart;
import com.shaoshaohuo.app.entity.EcCartItem;
import com.shaoshaohuo.app.framework.IViewFramework;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.adapter.CartAdapter;
import com.shaoshaohuo.app.ui.ec.SupplyDetailActivity;
import com.shaoshaohuo.app.view.EcCreateOrderPopupWindow;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.NumberUtil;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
/**
 * 购物车页面
 * @author YinSF
 * @createDate 2015-11-8
 */
public class EcCartFragment extends BaseFragment implements IViewFramework, OnClickListener {
    public EcCartFragment() {
    }
	@SuppressLint("ValidFragment")
    public EcCartFragment(Context mContext) {
	}

	private TopbarView topbar;
	private View view;
	private ListView listView;
	private CheckBox cbAllSelect;
	private CartAdapter cartAdapter;
	private TextView btnAllSelect;
	private TextView btnAllDelete;
	private List<EcCartItem> itemList;
	private String allSelectedItemIds;//所有被选中的商品id，以“，”分隔
	private String allSelectedItemUnits;//所有被选中的商品单位，以“，”分隔
	private String allSelectedItemPurchaseQuans;//所有被选中的商品采购量id，以“，”分隔
	private List<Integer> allSelectedIndex = new ArrayList<Integer>();//所有选中项目的序号
	private LinearLayout emptyDefaultLayout;
	private LinearLayout ecCartMenuLayout;
	private TextView tvTotalPrice;
	private EcCreateOrderPopupWindow createOrderPopupWindow;
	private Button createOrder;
	
	public static EcCartFragment sharedInstance(Context mContext) {
		return new EcCartFragment(mContext);
	}
	
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_cart, container, false);
		init();
		return view;
	}

	@Override
	public void init() {
		initView();
		initData();
		initListener();
	}

	@Override
	public void initView() {
		topbar = (TopbarView) view.findViewById(R.id.topbar);
		listView = (ListView) view.findViewById(R.id.list_view_cart);
		cbAllSelect = (CheckBox) view.findViewById(R.id.checkbox_ec_cart_all_select);
		btnAllSelect = (TextView) view.findViewById(R.id.btn_all_select);
		btnAllDelete = (TextView) view.findViewById(R.id.btn_all_delete);
		tvTotalPrice = (TextView) view.findViewById(R.id.tv_total_price);
		emptyDefaultLayout = (LinearLayout) view.findViewById(R.id.empty_default_view);
		ecCartMenuLayout = (LinearLayout) view.findViewById(R.id.layout_ec_cart_menu);
		createOrder = (Button) view.findViewById(R.id.create_order);
		createOrderPopupWindow = new EcCreateOrderPopupWindow(getActivity(), true);
	}

	@Override
	public void initData() {
		topbar.setCenterText("购物车");
		cartAdapter = new CartAdapter(getContext(), this, new ArrayList<EcCartItem>(), true);
		listView.setAdapter(cartAdapter);
		requestData();
	}

	public void requestData() {
		startLoadingDialog();
		RequestService.getInstance().ecCartList(getContext(), EcCart.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
                if (resultData.isOk()) {
                	EcCart cart = (EcCart) resultData;
                	if (cart.getData() != null && cart.getData().getList() != null && !cart.getData().getList().isEmpty()) {
                		itemList = cart.getData().getList();
                	} else {
                		itemList = new ArrayList<EcCartItem>();
                	}
                	showContentLayout();
                	cartAdapter.setData(itemList);
                	updateTotalPrice();
                } else {
                    showToast(resultData.getMsg());
                }
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
                showToast(getString(R.string.please_check_network));
			}
			
		});		
	}
	
	/**
	 * 根据数据加载情况，动态显示合适的布局
	 */
	public void showContentLayout() {
		if (itemList == null || itemList.isEmpty()) {
			emptyDefaultLayout.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			ecCartMenuLayout.setVisibility(View.GONE);
		} else {
			emptyDefaultLayout.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			ecCartMenuLayout.setVisibility(View.VISIBLE);
		}
	}
	/**
	 * 根据数据加载情况，动态显示合适的布局
	 */
	public void showContentLayout(boolean isEmpty) {
		if (isEmpty) {
			emptyDefaultLayout.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			ecCartMenuLayout.setVisibility(View.GONE);
		} else {
			emptyDefaultLayout.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			ecCartMenuLayout.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public void initListener() {
		cbAllSelect.setOnClickListener(this);
		btnAllSelect.setOnClickListener(this);
		btnAllDelete.setOnClickListener(this);
		createOrder.setOnClickListener(this);
		/*listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ViewHolder holder = (ViewHolder) view.getTag();
				// 改变CheckBox的状态
				holder.cbSelectItem.toggle();
				// 将CheckBox的选中状况记录下来
				CartAdapter.getIsSelected().put(position, holder.cbSelectItem.isChecked());		
				cartAdapter.notifyDataSetChanged();
			}
		});*/
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.checkbox_ec_cart_all_select:
		case R.id.btn_all_select:
			boolean isChecked = false;
			if (btnAllSelect.getText().equals("取消全选")) {
				isChecked = true;
			}
			if (isChecked) {
				btnAllSelect.setText("全选");
				cbAllSelect.setChecked(false);
			} else {
				btnAllSelect.setText("取消全选");
				cbAllSelect.setChecked(true);
			}
			for (int i = 0; i < cartAdapter.getCount(); i++) {
				((EcCartItem) cartAdapter.getItem(i)).setSelected(isChecked ? false : true);
			}
			cartAdapter.notifyDataSetChanged();
			break;
		case R.id.btn_all_delete:
			deleteAllSelected();
			break;
		case R.id.create_order:
			setAllSelectedItems();
			if (!StringUtil.isEmpty(allSelectedItemPurchaseQuans)) {
				String[] quanArr = allSelectedItemPurchaseQuans.split(",");
				for (String quan : quanArr) {
					if (StringUtil.isEmpty(quan) || "0".equals(quan)) {
						ToastUtil.toast("请输入购买数量");
						return;
					}
				}
			}
			if (StringUtil.isEmpty(allSelectedItemIds)) {
				ToastUtil.toast("您未选择要购买的商品，不能下单！");
				return;
			}
			createOrderPopupWindow.setSupplyid(allSelectedItemIds);
            createOrderPopupWindow.setCartUnits(allSelectedItemUnits);
            createOrderPopupWindow.setCartPurchaseQuantities(allSelectedItemPurchaseQuans);
            createOrderPopupWindow.showAtLocation(((ViewGroup)getActivity().findViewById(android.R.id.content)).getChildAt(0), Gravity.BOTTOM, 0, 0);
			break;
		default:
			break;
		}
	}

	private void deleteAllSelected() {
		setAllSelectedItems();
		if (StringUtil.isEmpty(allSelectedItemIds)) 
			return;
		AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
		dialog.setTitle("删除商品");
		dialog.setMessage("确定要从购物车中删除所有选中的商品吗？");
		dialog.setCancelable(false);
		dialog.setPositiveButton("确定", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (StringUtil.isEmpty(allSelectedItemIds)) return;
				startLoadingDialog();
				RequestService.getInstance().deleteFromEcCart(getContext(), allSelectedItemIds, BaseEntity.class, new RequestListener() {

					@Override
					public void onSuccess(int requestCode,
							BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							requestData();
						}
					}

					@Override
					public void onFailed(int requestCode,
							Exception error, String msg) {
						dismissLoadingDialog();
						ToastUtil.toast(msg);
					}
					
				});
			}
		});
		dialog.setNegativeButton("取消", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		dialog.show();
	}

	/**
	 * 设置所有选中的项目,下面这2个属性
	 * allSelectedItemIds
	 * allSelectedIndex
	 */
	private boolean setAllSelectedItems() {
		StringBuilder itemIds = new StringBuilder();
		StringBuilder itemUnits = new StringBuilder();
		StringBuilder itemQuantitys = new StringBuilder();
		allSelectedIndex.clear();
		for (int i = 0; i < cartAdapter.getCount(); i++) {
			EcCartItem item = (EcCartItem) cartAdapter.getItem(i);
			if (item.isSelected()) {
				/*if (StringUtil.isEmpty(item.getPurchase_quantity())) {
					return false;
				}*/
				if (itemIds.length() == 0) {
					itemIds.append(item.getGoods_id());
					itemUnits.append(item.getUnit());
					itemQuantitys.append(StringUtil.isEmpty(item.getPurchase_quantity()) ? "0" : item.getPurchase_quantity());
				} else {
					itemIds.append(",");
					itemIds.append(item.getGoods_id());
					itemUnits.append(",");
					itemUnits.append(item.getUnit());
					itemQuantitys.append(",");
					itemQuantitys.append(StringUtil.isEmpty(item.getPurchase_quantity()) ? "0" : item.getPurchase_quantity());
				}
				allSelectedIndex.add(i);
			}
		}
		allSelectedItemIds = itemIds.toString();
		allSelectedItemUnits = itemUnits.toString();
		allSelectedItemPurchaseQuans = itemQuantitys.toString();
		return true;
	}

	public void updateTotalPrice() {
		setAllSelectedItems();
		double totalPrice = 0;
		for (int i = 0; i < allSelectedIndex.size(); i++) {
			EcCartItem item = (EcCartItem) cartAdapter.getItem(allSelectedIndex.get(i));
			if (!StringUtil.isEmpty(item.getPurchase_quantity())) {
				totalPrice += Double.parseDouble(item.getUnitprice()) * Double.parseDouble(item.getPurchase_quantity());
			}
		}
		tvTotalPrice.setText("" + NumberUtil.formatMoney(totalPrice, NumberUtil.FORMAT_MONEY_CEIL));
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case SupplyDetailActivity.REQUEST_CODE_ADDRESS:
			if (resultCode == Activity.RESULT_OK) {
				createOrderPopupWindow.setAddress((Address) data.getExtras().get(ExtraName.address));
			}
			break;
		default:
			break;
		}
	}
	
	
}
